package com.flink.examples.functions;

import com.flink.examples.DataSource;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.windows.GlobalWindow;
import org.apache.flink.util.Collector;

import java.util.Iterator;
import java.util.List;

/**
 * @Description process算子：处理每个keyBy（分区）输入到窗口的批量数据流（为KeyedStream类型数据流）
 * @Author JL
 * @Date 2020/09/15
 * @Version V1.0
 */
public class Process {

    /**
     * 遍历集合，分别打印不同性别的总人数与年龄之和
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        List<Tuple3<String, String, Integer>> tuple3List = DataSource.getTuple3ToList();
        DataStream<String> dataStream = env.fromCollection(tuple3List)
                .keyBy((KeySelector<Tuple3<String, String, Integer>, String>) k -> k.f1)
                //按数量窗口滚动，每3个输入数据流，计算一次
                .countWindow(3)
                //处理每keyBy后的窗口数据流，process方法通常应用于KeyedStream类型的数据流处理
                .process(new ProcessWindowFunction<Tuple3<String, String, Integer>, String, String, GlobalWindow>() {
                    /**
                     * 处理窗口数据集合
                     * @param s         从keyBy里返回的key值
                     * @param context   窗口的上下文
                     * @param input     从窗口获取的所有分区数据流
                     * @param out       输出数据流对象
                     * @throws Exception
                     */
                    @Override
                    public void process(String s, Context context, Iterable<Tuple3<String, String, Integer>> input, Collector<String> out) throws Exception {
                        Iterator<Tuple3<String, String, Integer>> iterator = input.iterator();
                        int total = 0;
                        int i = 0;
                        while (iterator.hasNext()){
                            Tuple3<String, String, Integer> tuple3 = iterator.next();
                            total += tuple3.f2;
                            i ++ ;
                        }
                        out.collect(s + "共:"+i+"人，平均年龄：" + total/i);
                    }
                });
        dataStream.print();
        env.execute("flink Filter job");
    }

}
